import {createContext, ReactNode, useContext, useMemo, useState} from 'react';

interface SwitchTokenModalContextType {
  toggleModal: () => void;
  isSwitchTokenModalVisible: boolean;
}

const SwitchTokenModalContext = createContext<
  SwitchTokenModalContextType | undefined
>(undefined);

export const useSwitchTokenModalProvider = (): SwitchTokenModalContextType => {
  const context = useContext(SwitchTokenModalContext);
  if (!context) {
    throw new Error(
      'useSwitchTokenModalProvider must be used within an SwitchTokenModalProvider',
    );
  }
  return context;
};

export function SwitchTokenModalProvider({
  children,
}: Readonly<{
  children: ReactNode;
}>) {
  const [isSwitchTokenModalVisible, setIsSwitchTokenModalVisible] =
    useState<boolean>(false);
  const toggleModal = () => {
    setIsSwitchTokenModalVisible(pre => !pre);
  };

  const contextValue = useMemo(
    () => ({
      isSwitchTokenModalVisible,
      toggleModal,
    }),
    [isSwitchTokenModalVisible, toggleModal],
  );

  return (
    <SwitchTokenModalContext.Provider value={contextValue}>
      {children}
    </SwitchTokenModalContext.Provider>
  );
}
